package com.simple.relaxed.anno.impl;

import com.simple.relaxed.anno.AfterTask;
import com.simple.relaxed.anno.AsyncTask;
import com.simple.relaxed.anno.BeforeTask;
import com.simple.relaxed.manager.impl.AsyncTaskManager;

import java.lang.reflect.Method;

public class AsyncTaskImpl {

    /**
     * 搜索指定类中，的AsyncTask、BeforeTask、AfterTask注解标记的方法，并且注册到AsyncTaskManager中管理
     *
     * @param object 指定的对象
     */
    public static void asyncTask(Object object) {
        Class<?> aClass = object.getClass();
        Method[] methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            AsyncTask asyncTask = method.getDeclaredAnnotation(AsyncTask.class);
            BeforeTask beforeTask = method.getDeclaredAnnotation(BeforeTask.class);
            AfterTask afterTask = method.getDeclaredAnnotation(AfterTask.class);
            if (asyncTask != null) {
                AsyncTaskManager.Entry entry = AsyncTaskManager.getInstance().lookup(asyncTask.bindName());
                // 将方法增强为Runnable的run方法
                if (entry == null) {
                    entry = new AsyncTaskManager.Entry();
                    AsyncTaskManager.getInstance().register(asyncTask.bindName(), entry);
                }
                entry.setAsyncTask(method);
                entry.setAsyncInstance(object);
            } else if (beforeTask != null) {
                // 将方法增强为Runnable的run方法
                AsyncTaskManager.Entry entry = AsyncTaskManager.getInstance().lookup(beforeTask.bindName());
                if (entry == null) {
                    entry = new AsyncTaskManager.Entry();
                    AsyncTaskManager.getInstance().register(beforeTask.bindName(), entry);
                }
                entry.setBeforeTask(method);
                entry.setBeforeInstance(object);
            } else if (afterTask != null) {
                // 将方法增强为Runnable的run方法
                AsyncTaskManager.Entry entry = AsyncTaskManager.getInstance().lookup(afterTask.bindName());
                if (entry == null) {
                    entry = new AsyncTaskManager.Entry();
                    AsyncTaskManager.getInstance().register(afterTask.bindName(), entry);
                }
                entry.setAfterTask(method);
                entry.setAfterInstance(object);
            }
        }
    }
}
